/*
 * 从 output/坐骑训练经验.csv 同步 exp_per_training 到表 mount_level_experience
 * 仅更新 exp_per_training 字段
 */
import * as fs from "fs";
import * as path from "path";
import { createPool } from "mysql2/promise";

interface Row {
  level: number;
  expPerTraining: number;
}

function parseCsv(filePath: string): Row[] {
  const raw = fs.readFileSync(filePath, "utf8");
  const lines = raw.split(/\r?\n/).filter((l) => l.trim().length > 0);
  const rows: Row[] = [];
  for (let i = 1; i < lines.length; i++) {
    // 跳过表头
    const cols = lines[i].split(",");
    const level = Number(cols[0]);
    const exp = Number(cols[1]);
    if (Number.isFinite(level) && Number.isFinite(exp)) {
      rows.push({ level, expPerTraining: exp });
    }
  }
  return rows;
}

async function main() {
  const csvPath = path.resolve(process.cwd(), "output/坐骑训练经验.csv");
  if (!fs.existsSync(csvPath)) {
    console.error(`未找到CSV: ${csvPath}`);
    process.exit(1);
  }
  const data = parseCsv(csvPath);
  if (!data.length) {
    console.error("CSV解析为空");
    process.exit(1);
  }

  const host = process.env.DB_HOST || "43.143.253.188";
  const port = Number(process.env.DB_PORT || 3306);
  const user = process.env.DB_USER || "nextjs";
  const password = process.env.DB_PASS || "yEAiRE2jcxTyRBy5";
  const database = process.env.DB_NAME || "nextjs";

  const pool = await createPool({
    host,
    port,
    user,
    password,
    database,
    multipleStatements: true,
  });
  const conn = await pool.getConnection();
  try {
    await conn.beginTransaction();
    for (const r of data) {
      await conn.query(
        "UPDATE mount_level_experience SET exp_per_training = ? WHERE level = ?",
        [r.expPerTraining, r.level]
      );
    }
    await conn.commit();
    console.log(`✅ 已更新 ${data.length} 行 exp_per_training`);
  } catch (e: any) {
    await conn.rollback();
    console.error("❌ 更新失败:", e.message);
    process.exit(1);
  } finally {
    conn.release();
    await pool.end();
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

